import os
import sys
import logging
from google.appengine.ext import webapp
from globalmaptiles import GlobalMercator
from google.appengine.ext.webapp import template

class WMS2GMapsProxyHandler(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), '../templates/wms2gmapsproxy.html')
        self.response.out.write(template.render(path, {
                                                       'pagetitle' : 'My Garage | WMS 2 GMaps proxy',
                                                       'title' : 'WMS 2 GMaps proxy'}))

class WMS2GMapsHandler(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), '../templates/wms2gmaps.html')
        self.response.out.write(template.render(path, {
                                                       'pagetitle' : 'My Garage | WMS 2 GMaps',
                                                       'title' : 'WMS 2 GMapss'}))
                                                       
class WMSTilesHandler(webapp.RequestHandler):
    def get(self, type, z, x, y):
        self.z = int(z)
        self.x = int(x)
        self.y = int(y)
        tileUtil = GlobalMercator()
        if type == 'google' or type == 'osm':
            self.x, self.y = tileUtil.GoogleTile(self.x, self.y, self.z)
        
        #get tile bounds in web mercator EPSG:900913 coordinates
        xmin, ymin, xmax, ymax = tileUtil.TileBounds(self.x, self.y, self.z)
        #get all the query and post parameters sent to the form
        args = self.request.arguments()
        lowerCaseArgs = [(item, item.lower()) for item in args]
        lowerCaseArgsDict = dict([(j, self.request.get(i, None)) for i, j in lowerCaseArgs])
        
        bbox = '%d,%d,%d,%d' % (xmin, ymin, xmax, ymax)
        format = lowerCaseArgsDict.get('format', 'image/png')
        service = 'WMS'
        version = lowerCaseArgsDict.get('version', '1.1.1')
        request = 'GetMap'
        srs = lowerCaseArgsDict.get('srs', 'EPSG:4326')
        width = lowerCaseArgsDict.get('width', '256')
        height = lowerCaseArgsDict.get('height', '256')
        layers = lowerCaseArgsDict.get('layers', '')
        styles = lowerCaseArgsDict.get('styles', '')
        wmsurl = lowerCaseArgsDict.get('wmsurl', 'http://sampleserver1.arcgisonline.com/ArcGIS/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer/WMSServer')
        
        url = wmsurl + '?' + 'bbox=' + bbox + '&format=' + format + '&service=' + service + '&version=' + version + '&request=' + request + '&srs=' + srs + '&width=' + width + '&height=' + height
        if layers: url = url + '&layers=' + layers
        if styles: url = url + '&styles=' + styles
        self.redirect(url)